import React, { useState, useEffect } from 'react';
import { Popover, ColorPicker, message } from 'antd';

import { updateCanvas } from '../../api/canvas';
import { updateUserTheme } from '../../api/user';
import { THEME_COLORS, COLOR_PALETTE, generateThemeColors } from '../../constants';

import './header.css';
import User from './user/user';

const Header = ({ selectedCanvas, canvasTitle, onTitleChange, isEditing, id }) => {
    const [customColor, setCustomColor] = useState(
        localStorage.getItem('customColor') || THEME_COLORS.light.primary
    );
    // 添加网络状态
    const [isOnline, setIsOnline] = useState(navigator.onLine);

    // 处理颜色变化
    const handleColorChange = (color, shouldUpdateServer = true) => {
        const newColor = color.toHexString();
        setCustomColor(newColor);
        localStorage.setItem('customColor', newColor);

        // 更新 CSS 变量
        const root = document.documentElement;
        const newColors = generateThemeColors(newColor);
        Object.entries(newColors).forEach(([key, value]) => {
            root.style.setProperty(`--${key}`, value);
        });

        if (shouldUpdateServer && localStorage.getItem('token')) {
            // 用户已登录,更新数据库用户主题色字段
            updateUserTheme(newColor);
        }

        // 发送主题颜色变化的自定义事件
        const themeChangeEvent = new CustomEvent('theme-color-change', {
            detail: newColor,
            bubbles: true
        });
        document.dispatchEvent(themeChangeEvent);
    };

    // 从本地存储中取出主题色更新主题色(如果有的话)
    const updateColor = () => {
        const savedColor = localStorage.getItem('customColor');
        if (savedColor) {
            handleColorChange({ toHexString: () => savedColor }, false);
        }
    };

    // 初始化主题
    useEffect(() => {
        updateColor();
        // const savedColor = localStorage.getItem('customColor');
        // if (savedColor) {
        //   handleColorChange({ toHexString: () => savedColor });
        // }
    }, []);

    // 获取用户名
    const [username, setUsername] = useState('');

    useEffect(() => {
        // 初始时从localStorage获取用户名
        const storedUsername = localStorage.getItem('username');
        if (storedUsername) {
            setUsername(storedUsername);
        }

        // 添加登录事件监听
        const handleUserLogin = (event) => {
            setUsername(event.detail.username);
            // 只有当event.detail中包含theme时才更新主题色
            if (event.detail.theme) {
                handleColorChange({ toHexString: () => event.detail.theme }, false);
            }
        };

        // 添加登出事件监听
        const handleUserLogout = () => {
            // 登出后,清空主题色
            handleColorChange({ toHexString: () => THEME_COLORS.light.primary }, false);
            localStorage.removeItem('customColor');
            setUsername('');
        };

        // 注册事件监听器
        document.addEventListener('user-login', handleUserLogin);
        document.addEventListener('user-logout', handleUserLogout);

        // 清理函数
        return () => {
            document.removeEventListener('user-login', handleUserLogin);
            document.removeEventListener('user-logout', handleUserLogout);
        };
    }, []);

    // 添加网络状态监听
    useEffect(() => {
        const handleOnline = () => {
            setIsOnline(true);
            message.success('网络已连接');
        };

        const handleOffline = () => {
            setIsOnline(false);
            message.warning('网络已断开，已切换至离线模式');
        };

        window.addEventListener('online', handleOnline);
        window.addEventListener('offline', handleOffline);

        return () => {
            window.removeEventListener('online', handleOnline);
            window.removeEventListener('offline', handleOffline);
        };
    }, []);

    return (
        <div className="header">
            <div className="logo-container">
                <div className="logo">
                    <img src="/logo.png" />
                    <div>Canvas</div>
                </div>
                {username && <div className="username-display">欢迎, {username}</div>}
            </div>
            <div className="title-container">
                {selectedCanvas ? (
                    isEditing ? (
                        <input
                            type="text"
                            value={canvasTitle}
                            onChange={(e) => {
                                onTitleChange(e.target.value);
                            }}
                            onBlur={(e) => {
                                e.preventDefault();
                                onTitleChange(e.target.value, false, true);
                                updateCanvas(id, canvasTitle)
                                    .then((response) => {
                                        if (response && response.code === 200) {
                                            message.success('标题已保存');
                                        } else {
                                            message.warning('保存标题失败');
                                        }
                                    })
                                    .catch((error) => {
                                        message.error('保存标题失败');
                                    });
                            }}
                            onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                    onTitleChange(e.target.value, false, true);
                                    e.target.blur();
                                }
                            }}
                            autoFocus
                            className="title-input"
                        />
                    ) : (
                        <div
                            className="title-inputno-edit"
                            onClick={() => onTitleChange(canvasTitle, true)}
                        >
                            {canvasTitle}
                        </div>
                    )
                ) : (
                    <div className="title">我的画布</div>
                )}
            </div>
            <div className="theme-controls">
                <Popover
                    content={
                        <div className="color-palette">
                            {COLOR_PALETTE.map((color) => (
                                <div
                                    key={color}
                                    className="color-item"
                                    style={{ backgroundColor: color }}
                                    onClick={() => handleColorChange({ toHexString: () => color })}
                                />
                            ))}
                            <ColorPicker
                                value={customColor}
                                onChange={handleColorChange}
                                presets={[
                                    {
                                        label: '推荐',
                                        colors: COLOR_PALETTE
                                    }
                                ]}
                            />
                        </div>
                    }
                    trigger="click"
                    placement="bottomRight"
                >
                    <div
                        className="color-picker-trigger"
                        style={{ backgroundColor: customColor }}
                    />
                </Popover>
            </div>
            {/* 添加网络状态指示器 */}
            <div className="network-status">
                <span
                    className="status-dot"
                    style={{
                        backgroundColor: isOnline ? '#52c41a' : '#ff4d4f'
                    }}
                ></span>
                <span
                    className="status-text"
                    style={{
                        color: isOnline ? '#52c41a' : '#ff4d4f'
                    }}
                >
                    {isOnline ? '在线' : '离线模式'}
                </span>
            </div>
            <User></User>
        </div>
    );
};

export default Header;
